package com.quectel.core.module.partyeducationtraining.service.impl;


import com.quectel.constant.core.partyeducationtraining.TrainingConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partyeducationtraining.dao.TrainingDao;
import com.quectel.core.module.partyeducationtraining.dto.TrainingDto;
import com.quectel.core.module.partyeducationtraining.dto.TrainingPersonDto;
import com.quectel.core.module.partyeducationtraining.entity.TrainingEntity;
import com.quectel.core.module.partyeducationtraining.service.TrainingPersonService;
import com.quectel.core.module.partyeducationtraining.service.TrainingService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author ryan
 * @email ryan.ran@quectel.com
 * @date 2022/05/07 16:39
 */
@DubboService
public class TrainingServiceImpl implements TrainingService {

    private static final Logger LOGGER = LoggerFactory.getLogger(TrainingServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> TRAINING_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "TRAINING_CACHE_BY_ID:%d", id);

    @Autowired
    private TrainingDao trainingDao;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private TrainingPersonService trainingPersonService;

    @Override
    public TrainingDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                TRAINING_CACHE_BY_ID_FUNC.apply(id),

                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public TrainingDto selectById(Long id) {
        TrainingEntity entity = trainingDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, TrainingDto.class));
    }

    @Override
    public List<TrainingDto> queryList(Map<String, Object> params) {
        List<TrainingEntity> list = trainingDao.queryList(params);
        List<TrainingDto> result = CopyUtils.copyList(list, TrainingDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    private TrainingDto paddingField(TrainingDto dto) {
        final Date currentDate = new Date();
        if (dto != null) {
            PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectById(dto.getPartyId());
            dto.setParty(partyOrganizationDto);

            if (dto.getStartTime() != null && dto.getEndTime() != null) {
                if (currentDate.getTime() < dto.getStartTime().getTime()) {
                    dto.setStatus(TrainingConstants.StatusEnum.NOT_STARTED.getStatus());
                } else if (currentDate.getTime() > dto.getEndTime().getTime()) {
                    dto.setStatus(TrainingConstants.StatusEnum.ENDED.getStatus());
                } else {
                    dto.setStatus(TrainingConstants.StatusEnum.IN_PROGRESS.getStatus());
                }
            }
        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return trainingDao.queryTotal(params);
    }

    @Override
    @Lock(lockExpresses = RedisLockConstants.TRAINING_LOCK + "#{#dto.id}")
    public Long save(TrainingDto dto) {
        TrainingEntity entity = CopyUtils.copyObj(dto, TrainingEntity.class);
        entity.setId(Snowflake.nextId());

        entity.setTrainingItemCount(0);
        entity.setTrainingPersonCount(dto.getPersonIds() == null
                ? 0 : dto.getPersonIds().length);
        entity.setTrainingCompletePersonCount(0);
        entity.setTrainingCommentCount(0);
        entity.setPushStatus((byte) 0);

        trainingDao.insert(entity);

        if (dto.getPersonIds() != null) {
            Long[] personIds = dto.getPersonIds();
            List<TrainingPersonDto> trainingPersonDtos = Arrays.stream(personIds).map(personId -> {
                TrainingPersonDto newlyDto = new TrainingPersonDto();
                newlyDto.setTenantId(dto.getTenantId());
                newlyDto.setPartyId(dto.getPartyId());
                newlyDto.setTrainingId(entity.getId());
                newlyDto.setPartyPersonId(personId);
                newlyDto.setCompleteItemCount(0);
                newlyDto.setCompleteRate((byte) 0);
                return newlyDto;
            }).collect(Collectors.toList());
            trainingPersonService.saveBatch(trainingPersonDtos);
        }

        return entity.getId();
    }

    @Override
    @Lock(lockExpresses = RedisLockConstants.TRAINING_LOCK + "#{#dto.id}")
    public void updateById(TrainingDto dto) {
        TrainingEntity entity = CopyUtils.copyObj(dto, TrainingEntity.class);
        entity.setTrainingPersonCount(dto.getPersonIds() == null
                ? null : dto.getPersonIds().length);
        trainingDao.updateById(entity);

        if (dto.getPersonIds() != null) {
            trainingPersonService.deleteByTrainingId(entity.getId());
            Long[] personIds = dto.getPersonIds();
            List<TrainingPersonDto> trainingPersonDtos = Arrays.stream(personIds).map(personId -> {
                TrainingPersonDto newlyDto = new TrainingPersonDto();
                newlyDto.setTenantId(dto.getTenantId());
                newlyDto.setPartyId(dto.getPartyId());
                newlyDto.setTrainingId(entity.getId());
                newlyDto.setPartyPersonId(personId);
                newlyDto.setCompleteRate((byte) 0);
                return newlyDto;
            }).collect(Collectors.toList());
            trainingPersonService.saveBatch(trainingPersonDtos);
        }

        CacheKit.invalidRedisCache(TRAINING_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void updateAllColumnById(TrainingDto dto) {
        TrainingEntity entity = CopyUtils.copyObj(dto, TrainingEntity.class);


        MyBatisPlusUtils.updateAllColumnById(entity, trainingDao);

        CacheKit.invalidRedisCache(TRAINING_CACHE_BY_ID_FUNC.apply(dto.getId()));
    }

    @Override
    public void deleteById(Long id) {
        trainingDao.deleteById(id);

        CacheKit.invalidRedisCache(TRAINING_CACHE_BY_ID_FUNC.apply(id));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
            trainingPersonService.deleteByTrainingId(id);
        }
    }
}
